import logger from '@common/logger';
import { DELIVERY_TYPE } from '@constants/shop';
import dayjs from 'dayjs';

export const createDaysList = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
        result.push({
            text: getDayText(i),
            value: i,
        });
    }
    return result;
};

export const getDayText = (len) => {
    const time = dayjs().add(len, 'day');
    const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return `${time.format('MM-DD')}（${weeks[time.day()]}）`;
};


// 获取结算页所有的商品信息
export const getProductsList = (reviewList, isMain) => {
    console.log(reviewList);
    const result = [];
    for (let i = 0; i < reviewList.length; i++) {
        const { list } = reviewList[i];
        list.forEach(item => result.push({
            prod_id: item.prod_id,
            sku_id: item.sku_id,
            store_id: isMain ? 0 : item.store_id || 0,
        }));
    }
    return result;
};

// 更新结算页仓库信息
export const updateWarehouseInfo = () => {};


const calcExpressPrice = (item, info) => {
    let price = 0;
    if (!info) return price;
    const { additional, first } = info;
    const weight = item.weight * item.quantity;
    if (weight > 1) {
        price = (first - 0) + Math.ceil(weight - 1) * (additional - 0);
    } else {
        price = first - 0;
    }
    return price;
};

const calcCityExpressPrice = (item, infoList) => {
    const itemPrice = item.price * item.quantity;
    let priceResult = [];
    infoList.forEach(temp => {
        if (itemPrice >= (temp.start_fee - 0)) {
            priceResult.push(temp.express_fee - 0);
        }
    });
    return priceResult.length > 0 ? Math.min(...priceResult) : 0;
};

// 计算结算页所有的费用
export const calcAllReviewPrice = (reviewList=[]) => {
    let deliveryPrice = 0;
    let totalPrice = 0;
    for (let i = 0; i < reviewList.length; i++) {
        const { list } = reviewList[i];
        deliveryPrice += calcChildExpressPrice(reviewList[i]);
        list.forEach(item => {
            totalPrice += item.price * item.quantity;
        });
    }
    return {
        deliveryPrice: (deliveryPrice - 0).toFixed(2), // 配送费
        totalPrice: (totalPrice + (deliveryPrice - 0)).toFixed(2),
    };
};

// 修改预约时间 timeDays
export const chagneTimeDaysValue = (list, item, timeDaysValue) => {
    const result = [];
    for (let i = 0; i < list.length; i++) {
        const temp = list[i];
        if (temp.warehouseId === item.warehouseId && temp.deliveryType === item.deliveryType) {
            const _item = {
                ...temp,
                timeDays: timeDaysValue,
            };
            result.push(_item);
        } else {
            result.push(temp);
        }
    }
    return result;
};

// 修改单品的配送方式
export const chagneProductDeliveryType = (list, oldInfo, product, newType) => {
    // 获取仓库id，和仓库信息，根据仓库id和新的type 匹配是否已经有对应数据
    // 如果存在，直接在list中添加，原数据list减少
    // 如果不存在，拷贝一份仓库信息，然后新生成对象
    // 判断老的数据，减少后是否为空，如果为空，可直接修改当前类型
    const { warehouseId, deliveryType } = oldInfo;
    let result = [];
    if (deliveryType === newType) return [...list];
    // 是否存在目标对象
    const isTarget = list.filter(l => l.warehouseId === warehouseId && l.deliveryType === newType).length > 0;
    if (isTarget) {
        // 已经存在目标，一边剔除，一边添加
        list.forEach(item => {
            const isOldItem = item.warehouseId === warehouseId && item.deliveryType === deliveryType;
            const isTargetItem = item.warehouseId === warehouseId && item.deliveryType === newType;
            let tempItem = item;
            if (isOldItem) {
                if (item.list.length > 1) {
                    tempItem = {
                        ...item,
                        // 剔除当前对象
                        list: item.list.filter(o => o.prod_id !== product.prod_id && o.sku_id !== product.sku_id),
                    };
                } else {
                    tempItem = null;
                }
            }
            if (isTargetItem) {
                tempItem = {
                    ...item,
                    // 添加当前商品
                    list: [...item.list, product],
                };
            }
            tempItem && result.push(tempItem);
        });
    } else {
        // 不存在目标，需要生成目标
        // 构造新对象
        const info = {
            ...oldInfo,
            list: [product],
            deliveryType: newType,
        };
        list.forEach(temp => {
            const isOldTemp = temp.warehouseId === warehouseId && temp.deliveryType === deliveryType;
            let tempItem = temp;
            if (isOldTemp) {
                if (temp.list.length > 1) {
                    const tempList = temp.list.filter(o => {
                        if (o.sku_id === 0 && product.sku_id === 0) {
                            return o.prod_id !== product.prod_id;
                        } else {
                            return o.prod_id !== product.prod_id || o.sku_id !== product.sku_id;
                        }
                    });
                    tempItem = {
                        ...temp,
                        // 剔除当前对象
                        list: tempList,
                    };
                } else {
                    tempItem = null;
                }
            }
            tempItem && result.push(tempItem);
        });
        result.push(info);
    }

    return result;
};

const calcChildExpressPrice = (info) => {
    let deliveryPrice = 0;
    if (!info) return deliveryPrice;
    const { deliveryType, list, warehouseInfo } = info;
    if (deliveryType === DELIVERY_TYPE.SELF_PICK_UP) {
        return deliveryPrice;
    }
    let totalWeight = 0;
    let totalPrice = 0;
    // 计算包裹总重
    list.forEach(item => {
        switch(deliveryType) {
        case DELIVERY_TYPE.EXPRESS:
            totalWeight += item.weight * item.quantity / 1000;
            break;
        case DELIVERY_TYPE.CITY_EXPRESS:
            totalPrice += item.price * item.quantity;
            break;
        }
    });
    switch(deliveryType) {
    case DELIVERY_TYPE.EXPRESS:
        deliveryPrice = calcExpressPrice({ weight: totalWeight, quantity: 1 }, warehouseInfo.ordinary_express_config);
        break;
    case DELIVERY_TYPE.CITY_EXPRESS:
        deliveryPrice = calcCityExpressPrice({ price: totalPrice, quantity: 1 }, warehouseInfo.city_regions);
        break;
    }
    return deliveryPrice;
};

// 展示列表数据生成下单数据
export const reviewDataToOrderData = (list, isMain=false) => {
    const result = [];
    list.forEach((item, idx) => {
        result.push({
            details: item.list.map((temp, index) => {
                return {
                    id: `${idx}-${index}`,
                    prod_id: temp.prod_id,
                    sku_id: temp.sku_id,
                    quantity: temp.quantity,
                    origin: temp.price * temp.quantity,
                };
            }),
            p_store_id: isMain ? 0 : item.warehouseInfo.id || 0,
            warehouse_id: item.warehouseId,
            warehouse_name: item.warehouseName,
            deliver_type: item.deliveryType,
            booking_days: item.timeDays > -1 ? item.timeDays : 0,
            deliver_fee: calcChildExpressPrice(item),
        });
    });
    return result;
};


export const reviewBagListData = (list) => {
    const result = [];
    list.forEach((item, idx) => {
        item.list.forEach(temp => {
            result.push({
                prod_id: temp.prod_id,
                sku_id: temp.sku_id,
                quantity: 0,
            });
        });
    });
    return result;
};

// 生成失效数据和新数据
export const refreshReviewInvalidList = (list, info) => {
    const { warehouses, cart_prods } = info;
    // 有效的商品数据
    let validList = [];
    // 失效的商品数据
    let invalidList = [];
    if (warehouses) {
        // 如果存在 store
        // TODO 根据返回，更新菜品的新信息
        for (let i = 0; i < list.length; i++) {
            const item = list[i];
            // 遍历所有的字列表
            for (let j = 0; j < item.list.length; j ++) {
                const listItem = item.list[j];
                // 获取匹配的当前商品的匹配信息仓库id
                const tempWarehouseId = (cart_prods || []).filter(one => one.prod_id === listItem.prod_id && one.sku_id === listItem.sku_id)[0].warehouse_id;
                const tempList = warehouses.filter(temp => temp.warehouse_id === tempWarehouseId);
                if (tempList.length > 0) {
                    const warehouse = tempList[0];
                    // 根据配送方式判断
                    if (isValidItem(item, warehouse)) {
                        validList = refreshReviewListItemInfo(validList, item, listItem, warehouse);
                    } else {
                        invalidList = refreshReviewListItemInfo(invalidList, item, listItem, warehouse);
                    }
                } else {
                    invalidList.push(item);
                }
            }
        }
    } else {
        invalidList = list;
    }
    return {
        validList,
        invalidList,
    };
};

const isValidItem = (item, warehouse) => {
    let flag = true;
    switch(item.deliveryType) {
    case DELIVERY_TYPE.SELF_PICK_UP:
        flag = warehouse.pick_up;
        break;
    case DELIVERY_TYPE.EXPRESS:
        flag = warehouse.ordinary_express;
        break;
    case DELIVERY_TYPE.CITY_EXPRESS:
        flag = warehouse.city_express;
        break;
    default:
        flag = false;
        break;
    }
    return flag;
};


const refreshReviewListItemInfo = (list, item, listItem, info) => {
    let flag = false;
    const tempList = list.map(temp => {
        if (temp.deliveryType === item.deliveryType && temp.warehouseId === info.warehouse_id) {
            flag = true;
            return {
                ...temp,
                list: [...temp.list, listItem],
            };
        } else {
            return temp;
        }
    });
    if (!flag) {

        const dealInfo =  {
            warehouseName: info.name,
            warehouseId: info.warehouse_id,
            isCity: info.city_express, // 是否支持同城
            isCityBeyond: info.city_express && info.city_regions && info.city_regions.length === 0, // 是否是超出配送范围
            isExpress: info.ordinary_express, // 是否支持快递
            isPickUp: info.pick_up, // 是否支持自提
        };
        const result = {
            ...item,
            list: [listItem],
            warehouseInfo: info,
            ...dealInfo,
        };
        tempList.push(result);
    }
    return tempList;
};

export const replaceWarehouseInfo = (item, info) => {
    const dealInfo =  {
        warehouseName: info.name,
        warehouseId: info.warehouse_id,
        isCity: info.city_express, // 是否支持同城
        isCityBeyond: info.city_express && info.city_regions && info.city_regions.length === 0, // 是否是超出配送范围
        isExpress: info.ordinary_express, // 是否支持快递
        isPickUp: info.pick_up, // 是否支持自提
    };
    return {
        ...item,
        warehouseInfo: info,
        ...dealInfo,
    };
};

export const addCityRegionInfo = (list) => {
    const result = [];
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        result.push({
            ...item,
            isCityRegionLow: getIsLowCityExpress(item),
            cityRegionMinPrice: getMinCityExpressPrice(item.warehouseInfo.city_regions),
        });
    }
    return result;
};


export const getIsLowCityExpress = (item) => {
    const { deliveryType, list, warehouseInfo, isCity, isCityBeyond } = item;
    if (deliveryType === DELIVERY_TYPE.CITY_EXPRESS) {
        let totalPrice = 0;
        list.forEach(item => {
            totalPrice += item.price * item.quantity;
        });
        if (isCity && !isCityBeyond && totalPrice < getMinCityExpressPrice(warehouseInfo.city_regions)) {
            return true;
        }
    }
    return false;
};

export const getMinCityExpressPrice = (list) => {
    // express_fee: "2"
    // start_fee: "1"
    let result = [];
    for (let i = 0; i < list.length; i++) {
        result.push(list[i].start_fee - 0);
    }
    return result.length > 0 ? Math.min(...result) : 0;
};
